<template>
  <el-date-picker
      v-model="value"
      :type="selectType"
      :format="formatType"
      value-format="YYYY-MM-DD"
      start-placeholder="开始时间"
      end-placeholder="结束时间"
      placeholder="选择日期"
      @change="submit"
      v-if="isSelect"
  />
  <div ref="myChart"
       v-loading="isLoading"
       class="chart-box"></div>
</template>

<script>
import {GetDailyTraffic} from "@/http/dashboard/dashboard";
import dayjs from "dayjs";
import {GetTimeZone, GetTop10} from "../http/dashboard/dashboard";

export default {
name: "Echart",
  props:{
    type:String,
  },
  data(){
    return{
      value:'',
      baseUrl:'',
      isLoading:false,
      optionTem:{
        title: { text: "总访问量" },
        tooltip: {},
        xAxis: {
          data: [],
        },
        yAxis: {},
        series: [
          {
            name: "用户量",
            type: "line",
            data: [],
          },
        ],
      },
    }
  },
  computed:{
    selectType(){
      let str;
      switch (this.type){
        case 'line':str = 'week';
        break;
        case 'bar':str = "daterange";
        break;
      }
      return str;
    },
    formatType(){
      let str;
      switch (this.type){
        case 'line':str = '[Week] ww';
          break;
        case 'bar':str = "MM-DD";
          break;
      }
      return str;
    },
    isSelect(){
      return this.type !== "pie";
    }
  },
  mounted() {
    if (this.type === 'pie'){
      this.pieChart();
    }else {
      this.getEchartData(this.optionTem)
    }
  },
  methods:{
    initOption(){
      this.optionTem={
        title: { text: "总访问量" },
        tooltip: {},
        xAxis: {
          data: [],
        },
        yAxis: {},
        series: [
          {
            name: "用户量",
            type: "line",
            data: [],
          },
        ],
      }
    },
    getEchartData(option) {
      this.isLoading = true;
      const chart = this.$refs.myChart
      if (chart) {
        const myChart = this.$echarts.init(chart)
        myChart.setOption(option)
        window.addEventListener("resize", function() {
          myChart.resize()
        })
        this.isLoading=false;
      }
      // this.$on('hook:destroyed',()=>{
      //   window.removeEventListener("resize", function() {
      //     myChart.resize();
      //   });
      // })
    },
    submit(){
      if (this.value === null){
        this.initOption()
        this.getEchartData(this.optionTem)
        return;
      }
      switch (this.type){
        case 'line':
          this.lineChart();
          break
        case 'bar':
          this.barChart();
          break;
        case 'pie':
          this.pieChart();
          break
      }
    },
    lineChart(){
      GetDailyTraffic(this.value).then(res=>{
        const {code,data} = res.data;
        if (code === 200){
          this.dataToLocal(data);
        }
      })
    },
    barChart(){
      GetTop10(this.value[0],this.value[1]).then(res=>{
        const {code,data} = res.data;
        if (code === 200){
          this.top10ToChart(data)
        }
      })
    },
    pieChart(){
      GetTimeZone().then(res=>{
        const {code,data} = res.data;
        if (code === 200){
          let str=["0:00-8:59","9:00-13:59","14:00-20:59","21:00-23:59"]
          let opData=[];
          for (let i = 0; i < 4; i++) {
            let op = {value:data[i],name:str[i]}
            opData.push(op);
          }
          let optionTem = {
            tooltip: {
              trigger: 'item'
            },
            legend: {
              top: '5%',
              left: 'center'
            },
            series: [
              {
                name: '访问量',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                  borderRadius: 10,
                  borderColor: '#fff',
                  borderWidth: 2
                },
                label: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  label: {
                    show: true,
                    fontSize: '40',
                    fontWeight: 'bold'
                  }
                },
                labelLine: {
                  show: false
                },
                data: opData
                  // { value: 1048, name: 'Search Engine' },
                  // { value: 735, name: 'Direct' },
                  // { value: 580, name: 'Email' },
                  // { value: 484, name: 'Union Ads' },
                  // { value: 300, name: 'Video Ads' }

              }
            ]
          };
          if (optionTem.series.data!==[]){
            this.getEchartData(optionTem);
          }
        }
      })
    },
    dataToLocal(data){
      let option = new Map();
      let t = this.value;
      t = dayjs(t).format("MM-DD")
      for (let i = 0; i < 7; i++) {
        option.set(t,0)
        t = dayjs(t).add(1,'day').format("MM-DD")
      }
      for(let i in data){
        let key = dayjs(data[i].opDate).format("MM-DD")
        option.set(key,data[i].count)
      }
      let result={d1:[],d2:[]}
      for (const item of option) {
        result.d1.push(item[0])
        result.d2.push(item[1])
      }
      this.getEchartData(this.optionConstructor(result.d1,result.d2,"访问量","line"))
    },
    top10ToChart(data){
      let result = {d1:[],d2:[]}
      for (const item of data) {
        result.d1.push(item.ipAddress)
        result.d2.push(item.count)
      }
      this.getEchartData(this.optionConstructor(result.d1,result.d2,"访问量","bar"))
    },
    optionConstructor(d1,d2,title,type){
      let option = this.optionTem;
      option.xAxis.data=d1;
      option.series[0].data = d2
      option.series[0].type = type;
      option.title.text = title
      return option;
    }
  },
  watch:{
    // value(val){
    //   if (val === null ){
    //     console.log(111)
    //     // this.getEchartData(this.optionTem);
    //   }
    // }
  }
}
</script>

<style scoped>
.chart-box{
  width: 60vw;
  height: 30vw;
  margin: 0 auto;
}
</style>